import React from 'react';
import { Drawer, Form, Input, Button, Space, message, Select, Divider } from 'antd';
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';
import { FormInstance } from 'antd/lib/form';

import { StrategyInfo } from '../../../../schema/Strategy';
import { createStrategy, modifyStrategy } from '../../../../servers/servers';
import { verifyNull } from 'utils/tools';

const { Option } = Select;

/**
 * 策略项props
 */
interface IProps {
  /**提交函数结束后的回调,编辑需要传obj，判断是否跳第一页 */
  callback: (obj?: any) => any;
}

/**
 * 策略项state
 */
interface IState {
  // 当前的操作类型为新增还是编辑
  mode: 'create' | 'modify';
  // 当前操作弹出抽屉的可见性
  visible: boolean;
}

/**
 * 策略项管理操作
 */
export class StrategyOperationDrawer extends React.Component<IProps, IState> {
  // 表单引用
  private formRef: React.RefObject<FormInstance>;

  // 当前的策略项信息
  private StrategyInfo?: StrategyInfo;

  constructor(props: IProps) {
    super(props);
    this.formRef = React.createRef<FormInstance>();
    this.state = {
      ...props,
      mode: 'create',
      visible: false,
    };
  }

  /**
   * 展开抽屉并设置类型
   */
  public open(mode: 'create' | 'modify'): void {
    this.setState({
      visible: true,
      mode: mode,
    });
  }

  /**
   * 关闭抽屉
   */
  public close(): void {
    this.formRef.current?.resetFields();
    this.setState({
      visible: false,
    });
  }

  /**
   * 设置表单值
   */
  public setValue(val: StrategyInfo) {
    setTimeout(() => {
      if (!val.values?.length) {
        val.values?.push({
          key: '',
          value: '',
        });
      }
      this.StrategyInfo = val;
      this.formRef.current?.setFieldsValue(val);
    }, 0);
  }

  /**
   * 提交 新增/编辑 的数据
   */
  private submitData(): void {
    const form = this.formRef.current;
    form?.validateFields().then(res => {
      const val = form.getFieldsValue() as StrategyInfo;
      // val.values需要做特殊处理，数据项为null和undefined，key不存在的数据，需要被过滤掉
      const ary = val.values;
      const filterAry: any = ary?.filter(item => item && item.key);
      val.values = filterAry;
      console.log(val, '提交的数据');

      if (this.state.mode === 'create') {
        createStrategy(val)
          .then(res => {
            if (res.code === 0) {
              message.success('创建成功');
              this.close();
              this.props.callback();
            } else {
              message.error(`${res.tips}(错误码:${res.code})`);
            }
          })
          .catch(error => {
            console.error(`系统异常: ${JSON.stringify(error)}`);
          });
      } else {
        const strategyOptionId = this.StrategyInfo?.strategyOptionId as number;
        modifyStrategy(strategyOptionId, val)
          .then(res => {
            if (res.code === 0) {
              message.success('修改成功');
              this.close();
              this.props.callback(strategyOptionId);
            } else {
              message.error(`${res.tips}(错误码:${res.code})`);
            }
          })
          .catch(error => {
            console.error(`系统异常: ${JSON.stringify(error)}`);
          });
      }
    });
  }

  /**
   * 渲染抽屉底部footer
   */
  private buildFooter(): JSX.Element {
    return (
      <div className="drawer-footer-buttongroup">
        <Button
          type="primary"
          onClick={() => {
            this.submitData();
          }}
        >
          确定
        </Button>
        <Button
          onClick={() => {
            this.close();
          }}
        >
          取消
        </Button>
      </div>
    );
  }

  render() {
    const { visible, mode } = this.state;

    const layout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 16 },
    };

    return (
      <>
        {visible && (
          <Drawer
            width={500}
            visible={visible}
            onClose={() => {
              this.close();
            }}
            title={mode === 'create' ? '新建策略项' : '编辑策略项'}
            footer={this.buildFooter()}
          >
            <Form
              {...layout}
              layout="horizontal"
              ref={this.formRef}
              initialValues={{
                values: [{}],
              }}
            >
              <Form.Item
                label="策略项名称"
                name="strategyOptionName"
                rules={verifyNull('请输入策略项名称')}
                getValueFromEvent={event => {
                  return event.target.value.replace(/\s+/g, '');
                }}
              >
                <Input placeholder="请输入策略项名称" maxLength={30} />
              </Form.Item>
              <Form.Item label="类型" name="type">
                <Select placeholder="请选择类型">
                  <Option value="compare">比较</Option>
                </Select>
              </Form.Item>
              <Form.Item label="参考项名称" name="referName" rules={verifyNull('请输入参考项名称')}>
                <Input placeholder="请输入参考项名称" maxLength={30} />
              </Form.Item>
              <Form.Item label="参考列" name="referColumn" rules={verifyNull('请输入参考列')}>
                <Input placeholder="请输入参考列" maxLength={30} />
              </Form.Item>
              <Divider />
              <Form.List name="values">
                {(fields, { add, remove }) => {
                  return (
                    <div>
                      {fields &&
                        fields.map(field => (
                          <Space
                            key={field.key}
                            style={{ display: 'flex', marginBottom: 8 }}
                            align="baseline"
                          >
                            <Form.Item
                              {...field}
                              name={[field.name, 'key']}
                              fieldKey={[field.fieldKey, 'key']}
                              labelCol={{ span: 9 }}
                              label="显示名称"
                            >
                              <Input placeholder="请输入显示名称" maxLength={30} />
                            </Form.Item>
                            <Form.Item
                              {...field}
                              name={[field.name, 'value']}
                              fieldKey={[field.fieldKey, 'value']}
                              labelCol={{ span: 9 }}
                              label="显示值"
                            >
                              <Input placeholder="请输入显示值" maxLength={30} />
                            </Form.Item>

                            {fields.length > 1 && (
                              <MinusCircleOutlined
                                onClick={() => {
                                  remove(field.name);
                                }}
                              />
                            )}
                          </Space>
                        ))}
                      <Form.Item>
                        <Button
                          type="dashed"
                          onClick={() => {
                            add();
                          }}
                          block
                        >
                          <PlusOutlined /> 添加显示
                        </Button>
                      </Form.Item>
                    </div>
                  );
                }}
              </Form.List>
            </Form>
          </Drawer>
        )}
      </>
    );
  }
}
